package com.chuangke.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ResourceUtils;

import com.chuangke.common.exception.ChuangkeException;

@SuppressWarnings("deprecation")
public class FileUtils extends org.apache.commons.io.FileUtils {

	public static File getFile(String resourceLocation) {
		File file = null;
		try {
			file = ResourceUtils.getFile(resourceLocation);
		} catch (FileNotFoundException e) {
			throw new ChuangkeException(e);
		}
		return file;
	}

	public static String getFileStr(String resourceLocation) {
		File file = null;
		String fileString = null;
		try {
			file = ResourceUtils.getFile(resourceLocation);
			fileString = FileUtils.readFileToString(file, "UTF-8");
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
		return fileString;
	}

	public static String getSuffix(String originalFilename) {
		int index = originalFilename.lastIndexOf(".");
		return index != -1 ? originalFilename.substring(index + 1) : null;
	}

	public static String getFileName(String originalFilename) {
		int index = originalFilename.lastIndexOf(".");
		return index != -1 ? originalFilename.substring(0, index) : originalFilename;
	}

	public static void merge(String targetFile, String folder, String filename) {
		try {
			FileUtils.writeByteArrayToFile(new File(targetFile), new byte[] {});
			Files.list(Paths.get(folder)).filter(path -> !path.getFileName().toString().equals(filename))
					.sorted((o1, o2) -> {
						String p1 = o1.getFileName().toString();
						String p2 = o2.getFileName().toString();
						int i1 = p1.lastIndexOf("-");
						int i2 = p2.lastIndexOf("-");
						return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
					}).forEach(path -> {
						try {
							// 以追加的形式写入文件
							Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
							// 合并后删除该块
							Files.delete(path);
						} catch (IOException e) {
							e.printStackTrace();
						}
					});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void download(HttpServletResponse response, byte[] data) {
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			if (data != null) {
				os.write(data, 0, data.length);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
